package com.study_security.controller;

import com.study_security.domain.LoginUser;
import com.study_security.domain.ResponseResult;
import com.study_security.dto.MemberDTO;
import com.study_security.dto.ProjectDTO;
import com.study_security.dto.TaskDTO;
import com.study_security.dto.UserDTO;
import com.study_security.entity.Task;
import com.study_security.mapper.UserMapper;
import com.study_security.service.TaskService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/api/tasks")
//@PreAuthorize("hasAnyAuthority('perm_review','perm_leader','perm_member')")
public class TaskController {

    @Autowired
    private TaskService taskService;

    @Autowired
    UserMapper userMapper;
    /**
     * 根据项目名查找项目下的所有任务
     *
     * @param projectName 项目名
     * @return 项目下的所有任务
     */
    @GetMapping("/search")
    public List<TaskDTO> getTasksByProjectName(@RequestParam String projectName) {
        return taskService.getTasksByProjectName(projectName);
    }

    @GetMapping("/project/{projectId}/tasks")   // /project/1/...
    public List<TaskDTO> getProjectTasks(@PathVariable Long projectId) {
        return taskService.getTasksByProjectId(projectId);
    }

    @PreAuthorize("hasAnyAuthority('perm_leader','perm_member')")
    @GetMapping("/projects")
    public List<ProjectDTO> getUserProjects(Authentication authentication) {
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        return taskService.selectUserProjects(userId);
    }

    @PreAuthorize("hasAuthority('perm_leader')")
    @PostMapping("/add")
    public ResponseEntity<String> addTask(@RequestBody Task task) {

        boolean isAdded = taskService.addTask(task);
        return isAdded ? ResponseEntity.ok("任务添加成功！") : ResponseEntity.status(HttpStatus.BAD_REQUEST).body("任务添加失败。");
    }

    /**
     * 更新任务状态
     *
     * @param taskId 任务ID
     * @return 更新任务结果
     */
    @PreAuthorize("hasAnyAuthority('perm_leader','perm_member')")
    @PutMapping("/update/{taskId}")
    public ResponseEntity<String> updateTaskStatus(@PathVariable Long taskId,Authentication authentication) {
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        UserDTO userDTO=userMapper.selectUserInfoById(userId);
        String userRole=userDTO.getUserRole();
        if (!Objects.equals(userRole, "项目负责人") &&taskService.taskIdUserIdExisits(taskId,userId)) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("不可以提交别人的任务");

        }
        boolean isUpdated = taskService.updateTaskStatus(taskId);
        return isUpdated ? ResponseEntity.ok("任务状态更新成功！") : ResponseEntity.status(HttpStatus.BAD_REQUEST).body("任务状态更新失败。");
    }

    @GetMapping("/project/{projectId}/members")
    public List<MemberDTO> getProjectMembers(@PathVariable Long projectId) {
        return taskService.getProjectMembers(projectId);
    }

    @PreAuthorize("hasAnyAuthority('perm_leader','perm_member')")
    @DeleteMapping("/remove/{taskId}")
    public ResponseEntity<String> deleteTask(@PathVariable Long taskId,Authentication authentication) {
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        UserDTO userDTO=userMapper.selectUserInfoById(userId);
        String userRole=userDTO.getUserRole();
        if (!Objects.equals(userRole, "项目负责人") &&taskService.taskIdUserIdExisits(taskId,userId)) {

            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("不可以删除别人的任务");
        }
        boolean isDeleted = taskService.deleteTask(taskId);

        return isDeleted ? ResponseEntity.ok("任务删除成功！") : ResponseEntity.status(HttpStatus.BAD_REQUEST).body("任务删除失败。");
    }


}